#include <rtthread.h>
#include <rtdevice.h>
#include "board.h"
#include "drv_gpio.h"
#include "net_app.h"
#include "global.h"
#include "fal.h"
#include "drv_spi.h"
#include "spi_flash_sfud.h"
#include "easyflash.h"
#include "scene_info_pool.h"

#define DBG_TAG              "main"
#define DBG_LVL              LOG_LVL_DBG
/**************  filesystem init *************/
static void spiflash_power_up()
{
//    rt_pin_mode ( PW_A,   PIN_MODE_OUTPUT);
//    rt_pin_write( PW_A,   PIN_LOW);
    rt_pin_mode(FLASH_WR, PIN_MODE_OUTPUT);
    rt_pin_write(FLASH_WR, PIN_LOW);
//    rt_pin_mode( PW_OT, PIN_MODE_OUTPUT_OD);
}
#include <dfs_fs.h>
static int spi_flash_init()
{
    spiflash_power_up();
    rt_pin_mode(FLASH_WR, PIN_MODE_OUTPUT);
    rt_pin_write(FLASH_WR, PIN_LOW);
    //rt_thread_delay(100);
    rt_hw_spi_device_attach("spi2","spi20",FLASH_CS_PORT,FLASH_CS_PIN);
    if(RT_NULL == rt_sfud_flash_probe("norflash","spi20"))
    {
        return -RT_ERROR;
    };
    return RT_EOK;
}

int filesystem_init(void)
{
		struct rt_device * flash_dev;
		struct rt_device *mtd_dev = RT_NULL;
   	if(spi_flash_init()==RT_EOK){
			fal_init();
			mtd_dev = fal_mtd_nor_device_create(FS_PARTITION_NAME);
			if (!mtd_dev)
			{
					LOG_E("Can't create a mtd device on '%s' partition.", FS_PARTITION_NAME);
			}
			else
			{
					/* littlefs */
					if (dfs_mount(FS_PARTITION_NAME, "/", "lfs", 0, 0) == 0)
					{
							LOG_I("Filesystem initialized!");
					}
					else
					{
							dfs_mkfs("lfs", FS_PARTITION_NAME);
							/* littlefs */
							if (dfs_mount(FS_PARTITION_NAME, "/", "lfs", 0, 0) == 0)
							{
									LOG_I("Filesystem initialized!");
							}
							else
							{
									LOG_E("Failed to initialize filesystem!");
							}
					}
			}
			
		}
	
    return 0;
}
extern int flashDB_cfg(void);
int flash_init(void)
{
    filesystem_init();
    flashDB_cfg();
		easyflash_init();
    return 0;
}
INIT_ENV_EXPORT(flash_init);
rt_event_t global_event=NULL;
int main(void)
{
		//rt_thread_mdelay(10000);
		global_event=rt_event_create("global_event",RT_IPC_FLAG_FIFO);
		reset_info_chk();
		show_using_sram_size();
		LOG_I("device_id: %s ver: %s", DEVICE_ID,SOFTWARE_VER);
		app_control_init(&g_app_ctrl);
		scene_info_pool_init();
		scene_timer_info_pool_init();
		//mass_usb_init();
		net_app_init();
			
//		while(1){
//			
//			
//			
//			rt_thread_mdelay(10);
//		}
}

int reboot(int argc, char** argv)
{
   NVIC_SystemReset();
    return 0;
}
MSH_CMD_EXPORT(reboot, reboot);

